﻿using FitnessClubManager.DAL;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace FitnessClubManager.BLL
{
    class GridLichSuGiaoDich
    {
        public string MaSanPham { get; set; }
        public DateTime DateFrom { get; set; }
        public string TuNgay
        {
            get
            {
                return string.Format("{0:dd/MM/yyyy}", DateFrom);
            }
        }
        public DateTime DateTo { get; set; }
        public string DenNgay { get { return string.Format("{0:dd/MM/yyyy}", DateTo); } }
        public int LoaiSanPham { get; set; }
        public string Loai { get { return ((LoaiSanPham == 0) ? "Thẻ - " : "Tủ - ") + MaSanPham; } }
        public string TinhTrang
        {
            get
            {
                return ((DateTo.Date < DateTime.Now.Date) ? "Hết hạn" :
                                                ((DateTo.Subtract(DateTime.Now.Date).Days < 7) ? "Sắp hết hạn" : "Còn hạn"));
            }
        }
    }
    class SanPhamForGrid
    {
        public string MaSanPham { get; set; }
        public string TenSanPham { get; set; }
        public string MaKhachHang { get; set; }
        public string NguoiSoHuu { get; set; }
        public string TinhTrang
        {
            get
            {
                if (NgayBatDau == null)
                    return "Chưa sử dụng";
                return ((NgayKetThuc.Value.Date < DateTime.Now.Date) ? "Hết hạn" :
                                                ((NgayKetThuc.Value.Date.Subtract(DateTime.Now.Date).Days < 7) ? "Sắp hết hạn" : "Còn hạn"));
            }
        }
        public DateTime? NgayBatDau { get; set; }
        public string NgayThue
        {
            get
            {
                if (NgayBatDau == null)
                    return "";
                else

                    return string.Format("{0:dd/MM/yyyy}", NgayBatDau);
            }
        }
        public DateTime? NgayKetThuc { get; set; }
        public string NgayHetHan
        {
            get
            {
                if (NgayKetThuc == null)
                    return "";
                else
                    return string.Format("{0:dd/MM/yyyy}", NgayKetThuc);
            }
        }
        public int SoTien { get; set; }
        public string NguoiBan { get; set; }
        public int LoaiThe { get; set; }
        public string ThaoTac { get { return "Xóa"; } }
    }
    class NuocGKForGrid
    {
        public string MaNuocGK { get; set; }
        public DateTime? NgayBan { get; set; }
        public string NgayBanStr
        {
            get
            {
                if (NgayBan == null)
                    return "";
                return string.Format("{0:dd/MM/yyyy hh:mm}", NgayBan);
            }
        }
        public string TenNuocGK { get; set; }
        public int SoLuong { get; set; }
        public int GiaNhap { get; set; }
        public int DonGia { get; set; }
        public string ThanhTien
        {
            get
            {
                return (SoLuong * DonGia).ToString().FormatCurrency();
            }
        }
        public string Lai
        {
            get
            {
                return (SoLuong * (DonGia - GiaNhap)).ToString().FormatCurrency();
            }
        }
        public int ThanhTienTongHop
        {
            get;
            set;
        }
        public string ThanhTienTongHopStr
        {
            get { return ThanhTienTongHop.ToString().FormatCurrency(); }
        }
        public int LaiTongHop
        {
            get;
            set;
        }
        public string LaiTongHopStr
        {
            get { return LaiTongHop.ToString().FormatCurrency(); }
        }
        public string NguoiBan { get; set; }
        public string TenDangNhap { get; set; }
        public string ThaoTac { get { return "Xóa"; } }
    }
    class BizDongNuocGK
    {
        public static bool Add(DongNuocGiaiKhat dongNuoc)
        {
            using (var db = new DBFitnessWinAppEntities())
            {
                var nuocGK = (from e in db.NuocGiaiKhats
                              where e.MaNuocGK == dongNuoc.MaNuocGK
                              select e).FirstOrDefault();
                if (nuocGK == null)
                    throw new Exception("Sản phẩm " + dongNuoc.MaNuocGK + "không tồn tại");
                nuocGK.SoLuong -= dongNuoc.SoLuong;
                db.DongNuocGiaiKhats.Add(dongNuoc);
                db.SaveChanges();
                return true;
            }
        }
        public static bool Delete(string maNuocGK, DateTime ngayBan, string tenDangNhap)
        {
            using (var db = new DBFitnessWinAppEntities())
            {
                var nuocGK = (from e in db.DongNuocGiaiKhats
                              where e.MaNuocGK == maNuocGK && e.NgayBan == ngayBan && e.TenDangNhap == tenDangNhap
                              select e).FirstOrDefault();
                if (nuocGK == null)
                    throw new Exception("Không tồn tại chi tiết sản phẩm này");
                db.DongNuocGiaiKhats.Remove(nuocGK);
                db.SaveChanges();
                return true;
            }
        }

        public static List<NuocGKForGrid> GetListTrongNgay(DateTime ngay, string tenDangNhap)
        {
            using (var db = new DBFitnessWinAppEntities())
            {
                DateTime batDauNgay = new DateTime(ngay.Year, ngay.Month, ngay.Day);
                DateTime ketThucNgay = new DateTime(ngay.Year, ngay.Month, ngay.Day, 23, 59, 59);
                var ls = from e in db.DongNuocGiaiKhats.Include("NuocGiaiKhat")
                         where e.NgayBan >= batDauNgay && e.NgayBan <= ketThucNgay &&
                         e.TenDangNhap == tenDangNhap
                         orderby e.NgayBan descending
                         select new NuocGKForGrid
                         {
                             DonGia = e.DonGia,
                             GiaNhap = e.GiaNhap,
                             MaNuocGK = e.MaNuocGK,
                             TenNuocGK = e.NuocGiaiKhat.TenNuocGK,
                             NgayBan = e.NgayBan,
                             SoLuong = e.SoLuong
                         };
                return ls.ToList();
            }
        }
    }
    class BizNuocGiaiKhat
    {
        public static List<NuocGiaiKhat> GetList()
        {
            using (var db = new DBFitnessWinAppEntities())
            {
                var list = from e in db.NuocGiaiKhats
                           orderby e.TenNuocGK
                           select e;
                return list.ToList();
            }
        }

        public static NuocGiaiKhat GetOne(string maNuocGK)
        {
            using (var db = new DBFitnessWinAppEntities())
            {
                var list = (from e in db.NuocGiaiKhats
                            where e.MaNuocGK == maNuocGK
                            select e).FirstOrDefault();
                return list;
            }
        }

        public static NuocGiaiKhat Add(string tenNuocGk, int giaBan,
            int giaNhap, int soLuong)
        {
            using (var db = new DBFitnessWinAppEntities())
            {
                try
                {
                    var nuoc = (from e in db.NuocGiaiKhats
                                where e.TenNuocGK == tenNuocGk
                                select e).FirstOrDefault();
                    if (nuoc != null)
                        return null;
                    nuoc = new NuocGiaiKhat
                    {
                        MaNuocGK = Guid.NewGuid().ToString(),
                        TenNuocGK = tenNuocGk,
                        GiaBan = giaBan,
                        GiaNhap = giaNhap,
                        SoLuong = soLuong
                    };
                    nuoc = db.NuocGiaiKhats.Add(nuoc);
                    db.SaveChanges();
                    return nuoc;
                }
                catch
                {
                    return null;
                }
            }
        }
        public static NuocGiaiKhat Edit(string maNuoc, string tenNuocGk, int giaBan,
            int giaNhap, int soLuong)
        {
            using (var db = new DBFitnessWinAppEntities())
            {
                try
                {
                    var nuoc = (from e in db.NuocGiaiKhats
                                where e.MaNuocGK == maNuoc
                                select e).FirstOrDefault();
                    if (nuoc == null)
                        return null;
                    nuoc.TenNuocGK = tenNuocGk;
                    nuoc.GiaBan = giaBan;
                    nuoc.GiaNhap = giaNhap;
                    nuoc.SoLuong = soLuong;
                    db.SaveChanges();
                    return nuoc;
                }
                catch
                {
                    return null;
                }
            }
        }

        public static bool Delete(string maNuoc)
        {
            using (var db = new DBFitnessWinAppEntities())
            {
                try
                {
                    var nuoc = (from e in db.NuocGiaiKhats
                                where e.MaNuocGK == maNuoc
                                select e).FirstOrDefault();
                    if (nuoc == null)
                        return false;
                    db.NuocGiaiKhats.Remove(nuoc);
                    db.SaveChanges();
                    return true;
                }
                catch
                {
                    return false;
                }
            }
        }

        public static List<NuocGKForGrid> ThongKeChiTiet(DateTime dateFrom, DateTime dateTo, string tenDangNhap = null)
        {
            using (var db = new DBFitnessWinAppEntities())
            {
                DateTime ngayBatDau = new DateTime(dateFrom.Year, dateFrom.Month, dateFrom.Day,
                    0, 0, 0);
                DateTime ngayKetThuc = new DateTime(dateTo.Year, dateTo.Month, dateTo.Day, 23, 59, 59);
                var ls = from e in db.DongNuocGiaiKhats
                         where e.NgayBan >= ngayBatDau && e.NgayBan <= ngayKetThuc

                         select e;
                if (!tenDangNhap.IsNullOrEmpty())
                    ls = from e in ls
                         where e.TenDangNhap == tenDangNhap
                         select e;
                var list = from e in ls
                           orderby e.NgayBan descending
                           select new NuocGKForGrid
                           {
                               DonGia = e.DonGia,
                               GiaNhap = e.GiaNhap,
                               MaNuocGK = e.MaNuocGK,
                               NgayBan = e.NgayBan,
                               NguoiBan = e.NguoiSuDung.HoTen,
                               TenDangNhap = e.NguoiSuDung.TenDangNhap,
                               SoLuong = e.SoLuong,
                               TenNuocGK = e.NuocGiaiKhat.TenNuocGK
                           };
                return list.ToList();
            }
        }

        public static List<NuocGKForGrid> ThongKeTongHop(DateTime dateFrom, DateTime dateTo, string Hoten = null, string tenDangNhap = null)
        {
            using (var db = new DBFitnessWinAppEntities())
            {
                DateTime ngayBatDau = new DateTime(dateFrom.Year, dateFrom.Month, dateFrom.Day,
                    0, 0, 0);
                DateTime ngayKetThuc = new DateTime(dateTo.Year, dateTo.Month, dateTo.Day, 23, 59, 59);
                IQueryable<NuocGKForGrid> ls;
                if (!tenDangNhap.IsNullOrEmpty())
                {
                    ls = from e in db.NuocGiaiKhats
                         select new NuocGKForGrid
                         {
                             MaNuocGK = e.MaNuocGK,
                             TenNuocGK = e.TenNuocGK,
                             NgayBan = null,
                             NguoiBan = Hoten,
                             SoLuong = (from s in e.DongNuocGiaiKhats
                                        where s.NgayBan >= ngayBatDau && s.NgayBan <= ngayKetThuc && s.NguoiSuDung.TenDangNhap == tenDangNhap
                                        group s by s.MaNuocGK into sgroup
                                        select sgroup.Sum(t => t.SoLuong)).FirstOrDefault(),
                             ThanhTienTongHop = (from s in e.DongNuocGiaiKhats
                                                 where s.NgayBan >= ngayBatDau && s.NgayBan <= ngayKetThuc && s.NguoiSuDung.TenDangNhap == tenDangNhap
                                                 group s by s.MaNuocGK into sgroup
                                                 select sgroup.Sum(t => t.SoLuong * t.DonGia)).FirstOrDefault(),
                             LaiTongHop = (from s in e.DongNuocGiaiKhats
                                           where s.NgayBan >= ngayBatDau && s.NgayBan <= ngayKetThuc && s.NguoiSuDung.TenDangNhap == tenDangNhap
                                           group s by s.MaNuocGK into sgroup
                                           select sgroup.Sum(t => t.SoLuong * (t.DonGia - t.GiaNhap))).FirstOrDefault(),

                         };

                    return ls.ToList();
                }
                else
                {
                    ls = from e in db.NuocGiaiKhats
                         select new NuocGKForGrid
                         {
                             MaNuocGK = e.MaNuocGK,
                             NgayBan = null,
                             TenNuocGK = e.TenNuocGK,
                             SoLuong = (from s in e.DongNuocGiaiKhats
                                        where s.NgayBan >= ngayBatDau && s.NgayBan <= ngayKetThuc
                                        group s by s.MaNuocGK into sgroup
                                        select sgroup.Sum(t => t.SoLuong)).FirstOrDefault(),
                             ThanhTienTongHop = (from s in e.DongNuocGiaiKhats
                                                 where s.NgayBan >= ngayBatDau && s.NgayBan <= ngayKetThuc
                                                 group s by s.MaNuocGK into sgroup
                                                 select sgroup.Sum(t => t.SoLuong * t.DonGia)).FirstOrDefault(),
                             LaiTongHop = (from s in e.DongNuocGiaiKhats
                                           where s.NgayBan >= ngayBatDau && s.NgayBan <= ngayKetThuc
                                           group s by s.MaNuocGK into sgroup
                                           select sgroup.Sum(t => t.SoLuong * (t.DonGia - t.GiaNhap))).FirstOrDefault(),
                         };
                    return ls.ToList();
                }

            }
        }
    }
    partial class BizKhachHang
    {
        public static KhachHang Add(string ho, string ten,
            string soDienThoai, string diaChi, string GhiChu)
        {
            using (var db = new DBFitnessWinAppEntities())
            {
                try
                {
                    KhachHang khachHang = new KhachHang();
                    khachHang.MaKhachHang = Guid.NewGuid().ToString();
                    khachHang.Ho = ho;
                    khachHang.Ten = ten;
                    khachHang.SoDienThoai = soDienThoai;
                    khachHang.DiaChi = diaChi;
                    khachHang.GhiChu = GhiChu;
                    khachHang = db.KhachHangs.Add(khachHang);
                    db.SaveChanges();
                    return khachHang;
                }
                catch
                {
                    throw new Exception("Lỗi thêm khách hàng");
                }
            }
        }
        public static KhachHang Update(KhachHang khachHang)
        {
            using (var db = new DBFitnessWinAppEntities())
            {
                try
                {
                    KhachHang kh = (from e in db.KhachHangs
                                    where e.MaKhachHang == khachHang.MaKhachHang
                                    select e).SingleOrDefault();
                    if (kh == null)
                        return null;
                    kh.Ho = khachHang.Ho;
                    kh.Ten = khachHang.Ten;
                    kh.SoDienThoai = khachHang.SoDienThoai;
                    kh.DiaChi = khachHang.DiaChi;
                    kh.GhiChu = khachHang.GhiChu;
                    db.SaveChanges();
                    return kh;
                }
                catch
                {
                    throw new Exception("Lỗi cập nhật khách hàng");
                }
            }
        }

        internal static bool Delete(string maKH)
        {
            using (var db = new DBFitnessWinAppEntities())
            {
                try
                {
                    var kh = (from e in db.KhachHangs
                              where e.MaKhachHang == maKH
                              select e).FirstOrDefault();
                    if (kh != null)
                    {
                        for (int i = 0; i < kh.LichSuGiaoDiches.Count; i++)
                        {
                            string maSanPham = kh.LichSuGiaoDiches.ElementAt(i).MaSanPham;
                            db.LichSuGiaoDiches.Remove(kh.LichSuGiaoDiches.ElementAt(i));
                            db.SaveChanges();
                            var sanPham = (from e in db.SanPhams
                                           where e.MaSanPham == maSanPham
                                           select e).FirstOrDefault();
                            if (sanPham != null)
                                if (sanPham.LichSuGiaoDiches == null || sanPham.LichSuGiaoDiches.Count == 0)
                                {
                                    db.SanPhams.Remove(sanPham);
                                    db.SaveChanges();
                                }
                        }
                        db.KhachHangs.Remove(kh);
                        db.SaveChanges();
                        return true;
                    }
                    return false;
                }
                catch
                {
                    return false;
                }
            }
        }
    }
    class BizSanPham
    {
        /// <summary>
        /// 
        /// </summary>
        /// <param name="maSanPham"></param>
        /// <param name="loaiSanPham"></param>
        /// <returns></returns>
        public static SanPham Add(string maSanPham, LOAISANPHAM loaiSanPham)
        {
            using (var db = new DBFitnessWinAppEntities())
            {
                try
                {
                    SanPham sp = (from e in db.SanPhams
                                  where e.MaSanPham == maSanPham
                                  select e).SingleOrDefault();
                    if (sp == null)
                    {
                        sp = new SanPham();
                        sp.MaSanPham = maSanPham;
                        sp.LoaiSanPham = (int)loaiSanPham;
                        sp = db.SanPhams.Add(sp);
                        db.SaveChanges();
                        return sp;
                    }
                    else
                        return null;
                }
                catch
                {
                    throw new Exception("Lỗi thêm thông tin thẻ/tủ");
                }
            }
        }
        public static bool Delete(string maSanPham)
        {
            using (var db = new DBFitnessWinAppEntities())
            {
                try
                {
                    SanPham sp = (from e in db.SanPhams
                                  where e.MaSanPham == maSanPham
                                  select e).SingleOrDefault();
                    if (sp == null)
                    {
                        return false;
                    }
                    else
                    {
                        db.SanPhams.Remove(sp);
                        db.SaveChanges();
                        return true;
                    }
                }
                catch
                {
                    return false;
                }
            }
        }
        public static List<SanPham> DanhSachTu()
        {
            using (var db = new DBFitnessWinAppEntities())
            {
                var ls = from e in db.SanPhams
                         where e.LoaiSanPham == (int)LOAISANPHAM.Tu
                         select e;
                return ls.ToList();
            }
        }
        public static List<SanPhamForGrid> DanhSachTuForGrid()
        {
            using (var db = new DBFitnessWinAppEntities())
            {
                List<SanPhamForGrid> danhSachTu = new List<SanPhamForGrid>();
                var ls = (from e in db.SanPhams
                          where e.LoaiSanPham == (int)LOAISANPHAM.Tu
                          select e).ToList();
                foreach (var item in ls)
                {
                    var giaoDichLatest = (from e in db.LichSuGiaoDiches
                                          where e.MaSanPham == item.MaSanPham
                                          orderby e.DateTo descending
                                          select e).FirstOrDefault();
                    if (giaoDichLatest != null)
                    {
                        var hoTen = string.IsNullOrEmpty(giaoDichLatest.KhachHang.Ho) ? "" : giaoDichLatest.KhachHang.Ho;
                        hoTen += " ";
                        hoTen += string.IsNullOrEmpty(giaoDichLatest.KhachHang.Ten) ? "" : giaoDichLatest.KhachHang.Ten;
                        int soNgay = (giaoDichLatest.DateTo - DateTime.Now).Days;
                        SanPhamForGrid tu = new SanPhamForGrid
                        {
                            MaSanPham = item.MaSanPham,
                            NgayBatDau = giaoDichLatest.DateFrom,
                            NgayKetThuc = giaoDichLatest.DateTo,
                            NguoiSoHuu = hoTen,
                            SoTien = giaoDichLatest.SoTien,
                        };
                        danhSachTu.Add(tu);
                    }
                    else
                    {
                        SanPhamForGrid tu = new SanPhamForGrid
                        {
                            MaSanPham = item.MaSanPham,
                            NgayBatDau = null,
                            NgayKetThuc = null
                        };
                        danhSachTu.Add(tu);
                    }
                }
                return danhSachTu.ToList();
            }
        }
        internal static List<SanPhamForGrid> ThongKeChiTiet(DateTime dateFrom, DateTime dateTo, LOAISANPHAM? loaiSanPham = null, string hoten = null, string tenDangNhap = null)
        {
            using (var db = new DBFitnessWinAppEntities())
            {
                DateTime ngayBatDau = new DateTime(dateFrom.Year, dateFrom.Month, dateFrom.Day,
                    0, 0, 0);
                DateTime ngayKetThuc = new DateTime(dateTo.Year, dateTo.Month, dateTo.Day, 23, 59, 59);
                var ls = from e in db.LichSuGiaoDiches
                         where e.DateFrom >= ngayBatDau && e.DateFrom <= ngayKetThuc
                         select e;
                if (loaiSanPham != null)
                    ls = from e in ls
                         where e.SanPham.LoaiSanPham == (int)loaiSanPham
                         select e;
                if (!tenDangNhap.IsNullOrEmpty())
                {
                    ls = from e in ls
                         where e.TenDangNhap == tenDangNhap
                         select e;
                    var list = from e in ls
                               orderby e.DateFrom descending
                               select new SanPhamForGrid
                               {
                                   MaKhachHang = e.MaKhachHang,
                                   MaSanPham = e.MaSanPham,
                                   TenSanPham = (e.SanPham.LoaiSanPham == (int)LOAISANPHAM.The ? "Thẻ - " : "Tủ - ") + e.MaSanPham,
                                   NgayBatDau = e.DateFrom,
                                   NgayKetThuc = e.DateTo,
                                   NguoiBan = hoten,
                                   NguoiSoHuu = (e.KhachHang.Ho == null ? "" : e.KhachHang.Ho) + " " + (e.KhachHang.Ten == null ? "" : e.KhachHang.Ten),
                                   SoTien = e.SoTien,
                                   LoaiThe = e.SoThang
                               };
                    return list.ToList();
                }
                else
                {
                    var list = from e in ls
                               orderby e.DateFrom descending
                               select new SanPhamForGrid
                               {
                                   MaKhachHang = e.MaKhachHang,
                                   MaSanPham = e.MaSanPham,
                                   TenSanPham = (e.SanPham.LoaiSanPham == (int)LOAISANPHAM.The ? "Thẻ - " : "Tủ - ") + e.MaSanPham,
                                   NgayBatDau = e.DateFrom,
                                   NgayKetThuc = e.DateTo,
                                   NguoiSoHuu = (e.KhachHang.Ho == null ? "" : e.KhachHang.Ho) + " " + (e.KhachHang.Ten == null ? "" : e.KhachHang.Ten),
                                   SoTien = e.SoTien,
                                   LoaiThe = e.SoThang,
                                   NguoiBan = e.NguoiSuDung.HoTen
                               };
                    return list.ToList();
                }
            }
        }
    }
    class BizLichSuGiaoDich
    {
        public static LichSuGiaoDich Add(string maSanPham, string maKhachHang,
            string tenDangNhap, int soThang, int soTien, DateTime dateFrom, DateTime dateTo)
        {
            using (var db = new DBFitnessWinAppEntities())
            {
                LichSuGiaoDich lichSu = (from e in db.LichSuGiaoDiches
                                         where e.MaSanPham == maSanPham &&
                                         e.MaKhachHang == maKhachHang &&
                                         e.DateFrom == dateFrom
                                         select e).SingleOrDefault();
                if (lichSu == null)
                {
                    lichSu = new LichSuGiaoDich();
                    lichSu.DateFrom = dateFrom;
                    lichSu.DateTo = dateTo;
                    lichSu.MaKhachHang = maKhachHang;
                    lichSu.MaSanPham = maSanPham;
                    lichSu.SoThang = soThang;
                    lichSu.SoTien = soTien;
                    lichSu.TenDangNhap = tenDangNhap;
                    lichSu = db.LichSuGiaoDiches.Add(lichSu);
                    db.SaveChanges();
                    return lichSu;
                }
                else
                    return null;
            }
        }

        public static LichSuGiaoDich GetOwnCard(string maThe)
        {
            using (var db = new DBFitnessWinAppEntities())
            {
                var lichSu = (from e in db.LichSuGiaoDiches.Include("KhachHang").Include("SanPham")
                              where e.MaSanPham == maThe &&
                              e.SanPham.LoaiSanPham == (int)LOAISANPHAM.The
                              orderby e.DateFrom descending
                              select e).FirstOrDefault();
                return lichSu;
            }
        }

        public static List<GridLichSuGiaoDich> GetHistory(string maKhachHang)
        {
            using (var db = new DBFitnessWinAppEntities())
            {
                var lichSuGiaoDich = (from e in db.LichSuGiaoDiches
                                      where e.MaKhachHang == maKhachHang
                                      orderby e.DateTo descending
                                      select new GridLichSuGiaoDich
                                      {
                                          MaSanPham = e.MaSanPham,
                                          DateFrom = e.DateFrom,
                                          DateTo = e.DateTo,
                                          LoaiSanPham = e.SanPham.LoaiSanPham
                                      }).ToList();

                return lichSuGiaoDich;
            }
        }

        public static LichSuGiaoDich GiaHanSanPham(LichSuGiaoDich lichSu)
        {
            return Add(lichSu.MaSanPham, lichSu.MaKhachHang, lichSu.TenDangNhap, lichSu.SoThang, lichSu.SoTien, lichSu.DateFrom,
                lichSu.DateTo);
        }

        public static bool IsChuaDangKy(string maTu, DateTime ngayDangKy)
        {
            using (var db = new DBFitnessWinAppEntities())
            {
                var lichSu = (from e in db.LichSuGiaoDiches.Include("KhachHang").Include("SanPham")
                              where e.MaSanPham == maTu
                              orderby e.DateTo descending
                              select e).FirstOrDefault();
                if (lichSu != null)
                    if (lichSu.DateTo >= ngayDangKy)
                        return false;
                    else
                        return true;
                else
                    return true;
            }
        }

        internal static bool Delete(string maKhachHang, string maSanPham, DateTime dateFrom)
        {
            using (var db = new DBFitnessWinAppEntities())
            {
                LichSuGiaoDich lichSu = (from e in db.LichSuGiaoDiches
                                         where e.MaSanPham == maSanPham &&
                                         e.MaKhachHang == maKhachHang &&
                                         e.DateFrom == dateFrom
                                         select e).SingleOrDefault();
                if (lichSu == null)
                    throw new Exception("Không thể xóa lịch sử thẻ/tủ");
                else
                {
                    var maKH = lichSu.MaKhachHang;
                    db.LichSuGiaoDiches.Remove(lichSu);
                    db.SaveChanges();
                    var sanPham = (from e in db.SanPhams
                                   where e.MaSanPham == maSanPham
                                   select e).FirstOrDefault();
                    if (sanPham != null)
                    {
                        if (sanPham.LichSuGiaoDiches == null || sanPham.LichSuGiaoDiches.Count == 0)
                        {
                            db.SanPhams.Remove(sanPham);
                            db.SaveChanges();
                        }
                    }
                    else
                        throw new Exception("Không thể xóa lịch sử thẻ/tủ");
                    var kh = (from e in db.KhachHangs
                              where e.MaKhachHang == maKH
                              select e).FirstOrDefault();
                    if (kh != null)
                    {
                        if (kh.LichSuGiaoDiches == null || kh.LichSuGiaoDiches.Count == 0)
                        {
                            db.KhachHangs.Remove(kh);
                            db.SaveChanges();
                        }
                    }
                    return true;
                }
            }
        }
    }
    class BizUtility
    {
        /// <summary>
        /// 
        /// </summary>
        /// <param name="khachHang"></param>
        /// <param name="sanPham"></param>
        /// <param name="soThang"></param>
        /// <param name="soTien"></param>
        /// <param name="dateFrom"></param>
        /// <param name="dateTo"></param>
        /// <returns>-1: Thẻ đã tồn tại. 1 Thành công</returns>
        public static int DangKyThe(KhachHang khachHang, SanPham sanPham,
            string tenDangNhap, int soThang, int soTien, DateTime dateFrom, DateTime dateTo)
        {
            using (var db = new DBFitnessWinAppEntities())
            {
                try
                {
                    SanPham sp = (from e in db.SanPhams
                                  where e.MaSanPham == sanPham.MaSanPham
                                  select e).SingleOrDefault();
                    if (sp != null)
                        return -1;
                    else
                    {
                        db.SanPhams.Add(sanPham);
                        db.KhachHangs.Add(khachHang);
                        LichSuGiaoDich lichSu = new LichSuGiaoDich();
                        lichSu.DateFrom = dateFrom.Date;
                        lichSu.DateTo = dateTo.Date;
                        lichSu.MaKhachHang = khachHang.MaKhachHang;
                        lichSu.MaSanPham = sanPham.MaSanPham;
                        lichSu.SoThang = soThang;
                        lichSu.SoTien = soTien;
                        lichSu.TenDangNhap = tenDangNhap;
                        db.LichSuGiaoDiches.Add(lichSu);
                        db.SaveChanges();
                        return 1;
                    }
                }
                catch
                {
                    throw new Exception("Lỗi đăng ký thẻ");
                }
            }
        }

        public static int RefeshData()
        {
            using (var db = new DBFitnessWinAppEntities())
            {
                var listKhachHang = (from e in db.KhachHangs
                           where e.LichSuGiaoDiches.Count == 0
                           select e).ToList();
                int t = listKhachHang.Count;
                foreach (var item in listKhachHang)
                {
                    db.KhachHangs.Remove(item);
                }
                db.SaveChanges();
                var listSanPham = (from e in db.SanPhams
                                   where e.LoaiSanPham == (int)LOAISANPHAM.The
                                   && e.LichSuGiaoDiches.Count == 0
                                   select e).ToList();
                t += listSanPham.Count;
                foreach (var item in listSanPham)
                {
                    db.SanPhams.Remove(item);
                }
                db.SaveChanges();
                return t;
            }
        }
    }
}
